﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects.DataClasses;
using System.Text;

using Data;
using EuphoricNation.Rewrite;
using EuphoricNation.Util;

namespace EuphoricNation.Page
{
    public class EntityPage<T> : EuphoricNationPage where T : ContentBase
    {
        private T _fullPageInfo = null;
        private T _basicPageInfo = null;

        protected virtual T FullPageInfo
        {
            get
            {
                if (_fullPageInfo != null)
                    return _fullPageInfo;
                else
                {
                    string contentName = GetContentName();

                    if (contentName == null)
                        return null;

                    _fullPageInfo = DataContext.Contents.OfType<T>().Where(c => c.Name == contentName && c.Live).FirstOrDefault();

                    return _fullPageInfo;
                }
            }
        }

        protected virtual T BasicPageInfo
        {
            get
            {
                if (_basicPageInfo != null)
                    return _basicPageInfo;
                else
                {
                    string contentName = GetContentName();

                    if (contentName == null)
                        return null;

                    _basicPageInfo = DataContext.Contents.OfType<T>().Where(c => c.Name == contentName && c.Live).FirstOrDefault();

                    return _basicPageInfo;
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            SetPageInfo<T>(FullPageInfo);
        }

        private string GetContentName()
        {
            string name = null;

            if (RewriteParameters.ContainsKey("name"))
                name = RewriteParameters["name"];

            if (string.IsNullOrEmpty(name))
                name = Server.UrlDecode(Useful.GetPathFromURL(Request.RawUrl).Split('/').TrimBlank().LastOrDefault()); // HACK HACK HACK

            return name;
        }
    }
}